package com.lw.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class FileUploadUtil {

    /**
     * 文件存放路径
     * @return
     */
    private static String generateFilePath(){
        //存放路径
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        //日期路径
        String dataStr = format.format(date);
        String filePath = System.getProperty("user.dir") + "/" + "files" +   "/" + dataStr + "/";
        return filePath;
    }

    /**
     * 生成文件名
     * @param originFileName
     * @return
     */
    private static String generateFileName(String originFileName){
        String prefix = originFileName.substring(originFileName.lastIndexOf(".") + 1);

        //文件uuid名
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString().replaceAll("-", "");
        String fileName = uuidStr + "." + prefix;

        return fileName;
    }

    /**
     * 从请求流中获取文件
     * @param request
     * @return
     */
    public static Map<String, MultipartFile> getFilesMap(HttpServletRequest request){
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        commonsMultipartResolver.setDefaultEncoding("utf-8");
        Map<String, MultipartFile> map = null;
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest mulReq = (MultipartHttpServletRequest) request;
            map = mulReq.getFileMap();
        }
        return map;
    }

    public static Map<String,String> uploadFiles(HttpServletRequest request){
        Map<String, MultipartFile> fileMap = getFilesMap(request);
        return uploadFiles(fileMap);
    }

    /**
     * 上传文件
     * @param fileMap
     * @return
     */
    public static Map<String,String> uploadFiles(Map<String, MultipartFile> fileMap){
        Map<String,String> fileUploadMap = new HashMap<>();
        if(fileMap!=null&&fileMap.size()>0){
            //存放路径
            String filePath = generateFilePath();
            File folder = new File(filePath);
            if(!folder.exists()){
                folder.mkdirs();
            }

            for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
                MultipartFile file = entry.getValue();
                if (null != file) {
                    //生成文件名
                    String filename = entry.getKey();
                    if (!StringUtils.isEmpty(filename) && !"file".equals(filename)) {
                        String fileName = generateFileName(filename);

                        try {
                            file.transferTo(new File(folder,fileName));
                            fileUploadMap.put(fileName,filePath);
                        } catch (Exception e) {
                            log.error("",e);
                        }
                    }
                }
            }
        }
        return fileUploadMap;
    }
}
